import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { User, Task, CarbonActivity } from '../types';

interface UserState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  tasks: Task[];
  activities: CarbonActivity[];
  setUser: (user: User) => void;
  updatePlanetState: (updates: Partial<User['planetState']>) => void;
  addTask: (task: Task) => void;
  completeTask: (taskId: string) => void;
  updateTaskProgress: (taskId: string, progress: number) => void;
  resetDailyTasks: () => void;
  addActivity: (activity: CarbonActivity) => void;
  updateCarbonFootprint: (value: number) => void;
  updateUserPoints: (points: number) => void;
  getActivitySummary: () => {
    totalEmissions: number;
    byCategory: Record<string, number>;
    recentActivity: CarbonActivity[];
  };
  login: (token: string, user: User) => void;
  logout: () => void;
  updateUser: (user: User) => void;
  saveUserData: () => Promise<void>;
}

// 创建一些示例任务数据
const mockTasks: Task[] = [
  {
    id: '1',
    title: '步行上班',
    description: '今天步行或骑自行车上班，减少碳排放',
    type: 'daily',
    reward: {
      greenEnergy: 50,
      carbonReduction: 2
    },
    progress: 0,
    completed: false,
    deadline: new Date(new Date().setHours(23, 59, 59, 999)),
    criteria: {
      type: 'steps',
      target: 8000,
      current: 0
    }
  },
  {
    id: '2',
    title: '节约用电',
    description: '将空调温度调高1度，减少能源消耗',
    type: 'daily',
    reward: {
      greenEnergy: 30,
      carbonReduction: 1.5
    },
    progress: 0,
    completed: false,
    deadline: new Date(new Date().setHours(23, 59, 59, 999)),
    criteria: {
      type: 'energy',
      target: 2,
      current: 0
    }
  },
  {
    id: '3',
    title: '每周植树',
    description: '在你的星球上种植一棵新树',
    type: 'weekly',
    reward: {
      greenEnergy: 100,
      carbonReduction: 5,
      trees: 1
    },
    progress: 0,
    completed: false,
    deadline: new Date(new Date().setDate(new Date().getDate() + 7)),
    criteria: {
      type: 'action',
      target: 1,
      current: 0
    }
  },
  {
    id: '4',
    title: '社区清洁日',
    description: '参与社区垃圾分类活动',
    type: 'community',
    reward: {
      greenEnergy: 80,
      carbonReduction: 3,
      waterQuality: 0.05
    },
    progress: 0,
    completed: false,
    criteria: {
      type: 'participation',
      target: 1,
      current: 0
    }
  }
];

// 示例碳足迹活动数据
const mockActivities: CarbonActivity[] = [
  {
    id: '1',
    date: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000), // 6天前
    category: '交通',
    description: '乘坐公共交通上班',
    value: 1.5
  },
  {
    id: '2',
    date: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000), // 5天前
    category: '饮食',
    description: '购买本地生产食品',
    value: 0.8
  },
  {
    id: '3',
    date: new Date(Date.now() - 4 * 24 * 60 * 60 * 1000), // 4天前
    category: '居住',
    description: '降低家庭供暖',
    value: 2.3
  },
  {
    id: '4',
    date: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3天前
    category: '交通',
    description: '使用私家车',
    value: 3.2
  },
  {
    id: '5',
    date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2天前
    category: '消费',
    description: '购买二手物品',
    value: 0.5
  },
  {
    id: '6',
    date: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1天前
    category: '饮食',
    description: '素食一天',
    value: 0.3
  },
  {
    id: '7',
    date: new Date(), // 今天
    category: '居住',
    description: '使用LED灯泡',
    value: 0.2
  }
];

// 创建示例用户数据
const mockUser: User = {
  id: '1',
  username: '环保达人',
  email: 'user@example.com',
  carbonFootprint: 25, // 修改为中等水平碳足迹
  greenEnergy: 500,
  achievements: [],
  tasks: mockTasks,
  planetState: {
    pollution: 0.3,
    biodiversity: 0.7,
    energy: {
      clean: 300,
      total: 500
    },
    buildings: [],
    trees: 50,
    waterQuality: 0.8
  }
};

// 将用户数据保存到服务器的函数
const saveUserDataToServer = async (user: User, token: string) => {
  try {
    if (!user || !token) return;

    const response = await fetch('http://localhost:3000/api/auth/updateUser', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        carbonFootprint: user.carbonFootprint,
        greenEnergy: user.greenEnergy,
        planetState: user.planetState,
        tasks: user.tasks,
        achievements: user.achievements
      })
    });

    if (!response.ok) {
      throw new Error('保存用户数据失败');
    }

    const data = await response.json();
    console.log('用户数据保存成功:', data.message);
    return data.user;
  } catch (error) {
    console.error('保存用户数据错误:', error);
    throw error;
  }
};

export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      tasks: mockTasks,
      activities: mockActivities, // 使用示例活动数据
      
      setUser: (user) => set({ user }),
      
      // 保存用户数据到服务器
      saveUserData: async () => {
        const state = get();
        if (state.user && state.token) {
          try {
            await saveUserDataToServer(state.user, state.token);
          } catch (error) {
            console.error('保存用户数据失败:', error);
          }
        }
      },
      
      updatePlanetState: (updates) => 
        set((state) => {
          const updatedState = {
            user: state.user ? {
              ...state.user,
              planetState: {
                ...state.user.planetState,
                ...updates
              }
            } : null
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),
        
      addTask: (task) =>
        set((state) => {
          const updatedState = {
            tasks: [...state.tasks, task]
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),
        
      completeTask: (taskId) =>
        set((state) => {
          // 查找任务（包括个性化挑战任务）
          const task = state.tasks.find(t => t.id === taskId);
          if (!task || task.completed) return state;

          // 更新用户状态
          const updatedUser = state.user ? {
            ...state.user,
            greenEnergy: state.user.greenEnergy + (task.reward.greenEnergy || 0),
            carbonFootprint: Math.max(0, state.user.carbonFootprint - (task.reward.carbonReduction || 0)),
            planetState: {
              ...state.user.planetState,
              trees: state.user.planetState.trees + (task.reward.trees || 0),
              waterQuality: Math.min(1, state.user.planetState.waterQuality + (task.reward.waterQuality || 0)),
              pollution: Math.max(0, state.user.planetState.pollution - 0.02)
            }
          } : null;

          // 添加一条活动记录
          if (task.reward.carbonReduction) {
            const activity: CarbonActivity = {
              id: Date.now().toString(),
              date: new Date(),
              category: task.type === 'challenge' ? '个性化挑战' : '环保行动',
              description: `完成任务: ${task.title}`,
              value: -task.reward.carbonReduction // 负值表示减少碳排放
            };

            get().addActivity(activity);
          }

          // 更新任务状态
          const updatedState = {
            user: updatedUser,
            tasks: state.tasks.map(t =>
              t.id === taskId
                ? { ...t, completed: true, progress: 100 }
                : t
            )
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),

      updateTaskProgress: (taskId, progress) =>
        set((state) => {
          const updatedState = {
            tasks: state.tasks.map(task =>
              task.id === taskId
                ? { 
                    ...task, 
                    progress: Math.min(100, progress),
                    criteria: {
                      ...task.criteria,
                      current: Math.floor(progress * task.criteria.target / 100)
                    }
                  }
                : task
            )
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),

      resetDailyTasks: () =>
        set((state) => {
          // 只保留非日常任务
          const nonDailyTasks = state.tasks.filter(task => task.type !== 'daily');
          
          const updatedState = {
            tasks: nonDailyTasks
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),
        
      addActivity: (activity) =>
        set((state) => {
          const updatedState = {
            activities: [...state.activities, activity],
            user: state.user ? {
              ...state.user,
              carbonFootprint: Math.max(0, state.user.carbonFootprint + activity.value) // 确保不会降到0以下
            } : null
          };
          
          // 保存到服务器
          setTimeout(() => get().saveUserData(), 500);
          
          return updatedState;
        }),
        
        // 更新碳足迹
        updateCarbonFootprint: (value) => 
          set((state) => {
            if (!state.user) return state;
            
            // 更新星球状态
            let pollutionChange = 0;
            let biodiversityChange = 0;
            
            // 根据碳足迹变化调整污染和生物多样性
            if (value < state.user.carbonFootprint) {
              // 碳足迹减少，减少污染，增加生物多样性
              pollutionChange = -0.05;
              biodiversityChange = 0.03;
            } else if (value > state.user.carbonFootprint) {
              // 碳足迹增加，增加污染，减少生物多样性
              pollutionChange = 0.05;
              biodiversityChange = -0.03;
            }
            
            const updatedState = {
              user: {
                ...state.user,
                carbonFootprint: value,
                planetState: {
                  ...state.user.planetState,
                  pollution: Math.max(0, Math.min(1, state.user.planetState.pollution + pollutionChange)),
                  biodiversity: Math.max(0, Math.min(1, state.user.planetState.biodiversity + biodiversityChange))
                }
              }
            };
            
            // 保存到服务器
            setTimeout(() => get().saveUserData(), 500);
            
            return updatedState;
          }),
          
          // 获取活动统计摘要
          getActivitySummary: () => {
            const state = get();
            const activities = state.activities || [];
            
            // 计算总排放量
            const totalEmissions = activities.reduce((total, activity) => total + activity.value, 0);
            
            // 按类别统计
            const byCategory: Record<string, number> = {};
            activities.forEach(activity => {
              byCategory[activity.category] = (byCategory[activity.category] || 0) + activity.value;
            });
            
            // 获取最近的活动，确保日期是Date对象
            const recentActivity = [...activities]
              .map(activity => ({
                ...activity,
                // 确保date是Date对象
                date: activity.date instanceof Date ? activity.date : new Date(activity.date)
              }))
              .sort((a, b) => {
                // 使用安全的方式排序日期
                const dateA = a.date instanceof Date ? a.date.getTime() : 0;
                const dateB = b.date instanceof Date ? b.date.getTime() : 0;
                return dateB - dateA;
              })
              .slice(0, 10);
            
            return {
              totalEmissions,
              byCategory,
              recentActivity
            };
          },

      login: (token, user) => set({ token, user, isAuthenticated: true }),
      
      logout: () => {
        // 在退出登录前保存用户数据
        const state = get();
        if (state.user && state.token) {
          saveUserDataToServer(state.user, state.token)
            .then(() => console.log('退出登录前数据保存成功'))
            .catch(err => console.error('退出登录前数据保存失败:', err));
        }
        
        // 然后清空状态
        set({ token: null, user: null, isAuthenticated: false });
      },
      
      updateUser: (user) => {
        set({ user });
        // 更新后保存到服务器
        setTimeout(() => get().saveUserData(), 500);
      },

      updateUserPoints: (points) => {
        const user = get().user;
        if (!user) return;

        set({
          user: {
            ...user,
            greenEnergy: user.greenEnergy + points
          }
        });

        // 保存更新后的用户数据
        get().saveUserData();
      },
    }),
    {
      name: 'user-storage',
    }
  )
); 